<?php

namespace app\api\controller\user;
use app\api\service\order\PaymentService;
use app\common\enum\order\OrderPayTypeEnum;
use app\common\enum\order\OrderTypeEnum;
use app\common\model\user\Grade as GradeModel;
use app\common\model\user\GradeLog;
use app\api\controller\Controller;

/**
 * 用户等级管理模型
 */
class Grade extends Controller
{
    /**
     * 可购买的等级列表
     * @return \think\response\Json
     */
    public function buyableLists()
    {
        $app_id = request()->app_id;
        $list = GradeModel::getBuyList($app_id);
        return $this->renderSuccess('', $list);
    }

    /*购买等级 */
    public function buy()
    {
        $grade_id = input('grade_id', 0);
        if (!$grade_id) {
            return $this->renderError('参数错误');
        }
        $grade = GradeModel::detail($grade_id);
        if (!$grade || $grade['is_delete'] || !$grade['price']) {
            return $this->renderError('等级不存在或不允许购买');
        }
        $ableGrade = GradeModel::getUpperList(request()->user_id);
        $is_up = false;
        foreach ($ableGrade as $item) {
            if ($item['grade_id'] == $grade_id) {
                $is_up = true;
                break;
            }
        }
        if (!$is_up) {
            return $this->renderError('您的当前等级高于要购买的等级');
        }
        //添加记录
        $user = $this->getUser();
        $log = GradeLog::create([
            "log_no" => "gl" . date("YmdHis") . rand(1000, 9999),
            "user_id" => request()->user_id,
            "old_grade_id" => $user['grade']['grade_id'] ?? 0,
            'new_grade_id' => $grade_id,
            'change_type' => GradeLog::TYPE_BUY,
            'grade_expired_type' => $grade['expired_type'],
            'price' => $grade['price'],
            'pay_type' => OrderPayTypeEnum::WECHAT,
            'change_status' => 0,
            'app_id' => request()->app_id
        ]);
        if ($log) {
            //生成支付参数
            $res = PaymentService::wechat($user, $log['log_no'], OrderTypeEnum::GRADE, 'wx', $grade['price'], 0);
            return $this->renderSuccess('', $res);
        } else {
            return $this->renderError('购买失败');
        }
    }
}